package com.liangtian.mdm.system.menu.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.liangtian.mdm.base.controller.BaseController;
import com.liangtian.mdm.base.utils.PlatForm;
import com.liangtian.mdm.base.utils.ResultObject;
import com.liangtian.mdm.base.utils.ShiroSessionUtils;
import com.liangtian.mdm.dm.common.pojo.ResponseMsg;
import com.liangtian.mdm.dm.model.model.Model;
import com.liangtian.mdm.dm.model.service.ModelService;
import com.liangtian.mdm.system.menu.model.Menu;
import com.liangtian.mdm.system.menu.model.MenuShow;
import com.liangtian.mdm.system.menu.model.TreeBuilder;
import com.liangtian.mdm.system.menu.service.MenuService;
import com.liangtian.mdm.system.permission.service.SysRoleService;
import com.liangtian.mdm.system.user.model.SysUser;
import com.liangtian.mdm.util.ConstantBean;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 菜单控制类
 *
 * @author hadoop
 */
@Controller
@RequestMapping("/menu")
public class MenuController extends BaseController {

    @Autowired
    MenuService menuService;
    @Autowired
    ModelService modelService;
    // Session中保存的当前登录用户的信息
    //@Value("${ConstantBean.CURRENT_SESSION_USER}")
    //private String ConstantBean.CURRENT_SESSION_USER;
    @Autowired
    SysRoleService sysRoleService;

    @ResponseBody
    @RequestMapping(value = "/createMenu", method = RequestMethod.POST)
    public ResultObject quertAllAttr(HttpServletRequest request) {
        String tableName = request.getParameter("tableName");
        ResultObject result = null;
        try {
            menuService.createMenu(tableName);
            result = new ResultObject(1, "创建成功", "创建失败");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 查询菜单
     *
     * @param request
     * @param attribute
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/queryMenu", method = RequestMethod.POST)
    public String queryMenu() {
        String json = null;
        try {
            // 获取session中用户
            SysUser user = ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER);
/**
 String roleId = String.valueOf(user.getUserId());
 List<SysRoleMenu>  selectNodeList = roleServiceImpl.getSelectNodeByUserId(roleId);
 //根据userid获取所在的安全组的菜单权限
 List<SysRoleMenu>  groupMenuList = roleServiceImpl.getSelectNodeByGroupId(roleId);
 selectNodeList.addAll(groupMenuList);
 ArrayList<String>  ids = new ArrayList<String> ();
 if (selectNodeList != null && selectNodeList.size() > 0) {
 for (SysRoleMenu sysRoleMenu : selectNodeList) {
 //					if (null != sysRoleMenu.getModelId() && !"".equals(sysRoleMenu.getModelId())) {
 //						Menu menu = new Menu();
 //						menu.setModel_id(sysRoleMenu.getModelId());
 //						menu.setMenu_type(sysRoleMenu.getMenuType());
 //						Menu queryMenu = menuServiceImp.queryMenuByModelIdMenuType(menu); //修改为触发器(update_role_menu)方式修改菜单权限表的menu_id
 //						if (null != queryMenu ) {
 //							if (!ids.contains(queryMenu.getMenu_id())) {
 //								ids.add(queryMenu.getMenu_id());
 //							}
 //						}else{
 //							System.out.println(queryMenu);
 //						}
 //						continue;
 //					}
 if (!ids.contains(sysRoleMenu.getMenuId())) {
 ids.add(sysRoleMenu.getMenuId());
 }
 }
 } else {
 return json;
 }
 long t4 = System.currentTimeMillis();
 Map<String, Object> map = new HashMap<>();
 map.put("idList", ids);
 List<MenuShow> menuLst=menuServiceImp.queryMenuShowByPermission(map);
 //			List<MenuShow> menuLst=menuServiceImp.quertMenu(); //查询菜单
 //			List<MenuShow> menuLst=menuServiceImp.queryMenuShow();
 json = JSON.toJSONString(menuLst);
 **/
            Map<String, Object> map = new HashMap<>();
            map.put("userId", user.getUserId());
            map.put("status", "0");
            List<MenuShow> menuLst = menuService.queryMenuShowByPermission(map);
            menuLst = TreeBuilder.buildListToTree(menuLst);
            json = JSON.toJSONString(menuLst);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return json;
    }

    /**
     * 点击三级菜单(审核,申请)检查路径是否存在
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/checkUrlIsExist", method = RequestMethod.POST)
    public boolean checkUrlIsExist(HttpServletRequest request) {
        String fileName = "";
        boolean isHas = false;
        // 菜单url
        String url = request.getParameter("url");
        //判断传过来的url是否含有am
        if (url.indexOf("am/") != -1) {
            //分类树 /am/T_1329/T_1329_treeTabMain.jsp?menu_url=/am/T_1329/T_1329_treeTabApply.jsp
            int isCatagoryTree = url.lastIndexOf("?");
            String path = (isCatagoryTree == -1) ? url : url.substring(0, isCatagoryTree);
            //文件路径
            fileName = PlatForm.getAbsolutePath() + path;
            isHas = new File(fileName).exists();
        } else if (url.indexOf("T_") != -1) {  //传过来的表名带有T_
            //说明传递过来的是表名
            String type = request.getParameter("ptype");
            String modelId = url.split("_")[1];//获取模型ing成
            Model model = modelService.selectByPk(modelId);
            String classType = model.getClassType();//获取模型类型
            if (classType.equals("0")) {//如果是列表
                String path = "/am/" + url + "/" + url + "_" + type + ".jsp";
                fileName = PlatForm.getAbsolutePath() + path;
            } else {
                if (type.equals("apply")) {
                    String path = "/am/" + url + "/" + url + "_treeTabApply.jsp";
                    fileName = PlatForm.getAbsolutePath() + path;
                } else if (type.equals("update")) {
                    String path = "/am/" + url + "/" + url + "_treeTabUpdate.jsp";
                    fileName = PlatForm.getAbsolutePath() + path;
                } else if (type.equals("approve")) {
                    String path = "/am/" + url + "/" + url + "_treeTabApprove.jsp";
                    fileName = PlatForm.getAbsolutePath() + path;
                } else if (type.equals("list")) {
                    String path = "/am/" + url + "/" + url + "_treeTabList.jsp";
                    fileName = PlatForm.getAbsolutePath() + path;
                }
            }
            isHas = new File(fileName).exists();
        } else {
            isHas = true;
        }
        return isHas;
    }

    /**
     * 查询菜单树
     *
     * @param request
     * @param attribute
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/queryMenuTree", method = RequestMethod.POST)
    public String queryMenuTree(Menu menu) {
        List<Menu> menuLst = new ArrayList<Menu>();
        ResultObject result = new ResultObject();
        try {
            menuLst = menuService.menuTree(menu); //查询菜单树
            result.setData(menuLst);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JSON.toJSONString(menuLst);
    }

    /**
     * 左侧列表查询
     *
     * @param menu
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/queryList", method = RequestMethod.POST)
    public JSONObject queryList(Menu menu) {
        PageInfo pageInfo = menuService.queryMenuByContion(menu);
        List l = pageInfo.getList();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("rows", l);// JSONArray
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    /**
     * 新增
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/insert", method = RequestMethod.POST)
    public JSONObject addMenu(HttpServletRequest request, Menu menu) {
        JSONObject jsonObject = new JSONObject();
        ResponseMsg<String> rMsg = new ResponseMsg<String>();
        try {
            menuService.insertMenuForm(menu);
            rMsg.setRspCode(0);
        } catch (Exception e) {
            e.printStackTrace();
            rMsg.setRspCode(-1);
        }
        jsonObject.put("rmsg", rMsg);
        return jsonObject;
    }

    /**
     * 根据modelId查询审核页面链接
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/queryMenuUrl", method = RequestMethod.POST)
    public ResultObject queryMenuUrl(HttpServletRequest request) {
        Menu menu = null;
        ResultObject result = null;
        Map<String, Object> param = new HashMap<>();
        try {
            String tableName = request.getParameter("tableName");
            String ptype = request.getParameter("ptype");
            if (tableName.indexOf("T_") != -1) { //传过来的表名带有T_
                tableName = tableName.split("_")[1];
                param.put("modelId", tableName);
                param.put("ptype", ptype);
            } else { //传过来的是自己开发是模块的链接
                if ("freeze".equals(ptype) || "active".equals(ptype)) {
                    ptype = "update";
                }
                if ("wl_lb".equals(tableName.toLowerCase()) && "approve".equals(ptype)) {//物料类别审核页面的超链接不对,这里拼出来的是wl_lb_approve.jsp,实际应该是wlLbShenHe.jsp
                    param.put("url", "wlLbShenHe");
                }
                //--edit by wangyk at 180625:如果是文档审核，做如下定制化处理，否则首页报js错误。
                else if ("doc_cms_content".equals(tableName.toLowerCase()) && "approve".equals(ptype)) {
                    param.put("url", "/system/sysContent/sysContentApprove.jsp");
                } else {
                    param.put("url", tableName.toLowerCase() + "_" + ptype); //按照一定规则命名的菜单链接 业务类型加操作类型  wl_wl_submit.jsp
                }
            }
            menu = menuService.queryMenuUrlByModelId(param);
            result = new ResultObject(menu);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 新增
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/updateStatus", method = RequestMethod.POST)
    public ResultObject updateStatus(Menu menu) {
        ResultObject result = null;
        try {
            menuService.updateMenuStatus(menu);
            result = new ResultObject(1, "操作成功", "操作失败");
        } catch (Exception e) {
            e.printStackTrace();
            result = new ResultObject(2, "操作成功", "操作失败");
        }
        return result;
    }

    /**
     * 新增
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getById", method = RequestMethod.POST)
    public String getById(Menu menu) {
        Menu menuOne = null;
        try {
            menuOne = menuService.queryMenuById(menu);
            if (menuOne.getpName() == null) {
                menuOne.setpName("Tree-Root");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JSON.toJSONString(menuOne);
    }

    /**
     * 编辑  修改
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public JSONObject update(Menu menu) {
        JSONObject jsonObject = new JSONObject();
        ResponseMsg<String> rMsg = new ResponseMsg<String>();
        try {
            menuService.updateMenu(menu);
            rMsg.setRspCode(0);
        } catch (Exception e) {
            e.printStackTrace();
            rMsg.setRspCode(-1);
        }
        jsonObject.put("rmsg", rMsg);
        return jsonObject;
    }

}
